package com.member.shop.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.member.common.core.domain.entity.SysDictData;
import com.member.common.enums.CollectionTypeEnum;
import com.member.common.enums.DeleteEnum;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.utils.DateUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.bean.BeanUtils;
import com.member.shop.domain.*;
import com.member.shop.dto.GoodsQueryDto;
import com.member.shop.dto.SysBizGoodsDto;
import com.member.shop.mapper.SysBizGoodsMapper;
import com.member.shop.mapper.SysBizGoodsSkuMapper;
import com.member.shop.service.*;
import com.member.shop.vo.*;
import com.member.system.service.ISysDictDataService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 *
 * @author lixinchen
 * @date 2024-01-05
 */
@Service
public class SysBizGoodsServiceImpl extends ServiceImpl<SysBizGoodsMapper, SysBizGoods> implements ISysBizGoodsService {
    @Resource
    private SysBizGoodsMapper sysBizGoodsMapper;
    @Resource
    private SysBizGoodsSkuMapper sysBizGoodsSkuMapper;
    @Resource
    private ISysBizUserCollectService sysBizUserCollectService;
    @Resource
    private ISysBizUserService sysBizUserService;
    @Resource
    private ISysBizGoodsSkuService goodsSkuService;
    @Resource
    private ISysDictDataService dictDataService;
    @Resource
    private ISysBizRecommendCategoryService recommendCategoryGoodsService;
    @Resource
    private ISysBizRecommendGoodsService recommendGoodsService;
    @Resource
    private ISysBizMarketPageCategoryService marketPageCategoryService;
    @Resource
    private ISysBizSeckillPageService sysBizSeckillPageService;
    @Resource
    private ISysBizSeckillGoodsPageService sysBizSeckillGoodsPageService;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public SysBizGoods selectSysBizGoodsById(Long id) {
        SysBizGoods sysBizGoods = sysBizGoodsMapper.selectSysBizGoodsById(id);
        List<SpecsData> specsDatas = new ArrayList<>();
        if (sysBizGoods != null) {
            List dataList = JSON.parseArray(sysBizGoods.getSpecsData(), SpecsData.class);

            for (Object o : dataList) {
                SpecsData item = (SpecsData) o;
                specsDatas.add(item);

            }
            sysBizGoods.setSpecsDataList(specsDatas);
        }
        return sysBizGoods;
    }

    /**
     * 查询商品列表
     *
     * @param queryWrapper 商品
     * @return 商品
     */
    @Override
    public List<SysBizGoods> selectSysBizGoodsList(LambdaQueryWrapper<SysBizGoods> queryWrapper) {
        return sysBizGoodsMapper.selectList(queryWrapper);
    }

    public List<SysBizGoods> selectSysBizGoodsList(QueryWrapper<SysBizGoods> queryWrapper) {
        return sysBizGoodsMapper.selectList(queryWrapper);
    }

    /**
     * 新增商品
     *
     * @param sysBizGoods 商品
     * @return 结果
     */
    @Override
    public int insertSysBizGoods(SysBizGoods sysBizGoods) {
        sysBizGoods.setCreateTime(DateUtils.getNowDate());
        sysBizGoods.setGoodsCode(UUID.randomUUID().toString());
        int insert = sysBizGoodsMapper.insert(sysBizGoods);
        Long id = sysBizGoods.getId();
        String formattedNum = String.format("%05d", id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        sysBizGoods.setGoodsCode("SP" + dateStr + formattedNum);
        System.out.println(formattedNum); // 输出 "00001"
        this.updateSysBizGoods(sysBizGoods);
        return insert;
    }

    /**
     * 修改商品
     *
     * @param sysBizGoods 商品
     * @return 结果
     */
    @Override
    public int updateSysBizGoods(SysBizGoods sysBizGoods) {
        sysBizGoods.setUpdateTime(DateUtils.getNowDate());
        return sysBizGoodsMapper.updateById(sysBizGoods);
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteSysBizGoodsByIds(Long[] ids) {
        return sysBizGoodsMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteSysBizGoodsById(Long id) {
        SysBizGoods sysBizGoods = new SysBizGoods();
        sysBizGoods.setId(id);
        sysBizGoods.setDeleted(OrderDeleteEnum.DELETE.getKey());
        sysBizGoods.setUpdateTime(DateUtils.getNowDate());
        return sysBizGoodsMapper.updateById(sysBizGoods);
    }

    /**
     * 查询商品列表
     *
     * @param sysBizGoods 商品
     * @return 商品集合
     */
    @Override
    public List<SysBizGoodsDto> selectSysBizGoodsList(SysBizGoods sysBizGoods) {
        List<SysBizGoodsDto> goodsList = sysBizGoodsMapper.selectSysBizGoodsList(sysBizGoods);
//        if (goodsList != null) {
//            for (SysBizGoodsDto bizGoods : goodsList) {
//                SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkuMapper.selectSalesStockCount(bizGoods.getId());
//                //实际销量
//                bizGoods.setSalesCount(0L);
//                //商品库存
//                bizGoods.setStockCount(0L);
//                if (sysBizGoodsSku != null) {
//                    //实际销量
//                    bizGoods.setSalesCount(sysBizGoodsSku.getSalesCount());
//                    //商品库存
//                    bizGoods.setStockCount(sysBizGoodsSku.getStockCount());
//                }
//
//            }
//        }
        return goodsList;
    }

    @Override
    public List<GoodsIndexVo> selectSysBizGoods(GoodsQueryDto goodsQueryDto, List<Long> ids) {
        List<GoodsIndexVo> goodsIndexVoList = new ArrayList<>();
        List<SysBizGoods> sysBizGoodsList = getSysBizGoods(goodsQueryDto, ids);
        if (CollectionUtils.isEmpty(sysBizGoodsList)) {
            return goodsIndexVoList;
        }
        //SysBizUser loginUser = null;
        //if (userId != null) {
        //    loginUser = sysBizUserService.selectSysBizUserById(userId);
        //}
        for (SysBizGoods sysBizGoods : sysBizGoodsList) {
            GoodsIndexVo goodsIndexVo = new GoodsIndexVo();
            BeanUtils.copyProperties(sysBizGoods, goodsIndexVo);
            //List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuMapper.selectList(new LambdaQueryWrapper<SysBizGoodsSku>().eq(SysBizGoodsSku::getGoodsId, sysBizGoods.getId()));
            //// 非会员
            //if (loginUser == null || loginUser.getUserRole() == 0) {
            //    sysBizGoodsSkus.sort(Comparator.comparing(SysBizGoodsSku::getNoMemberSalesPrice));
            //} else {
            //    sysBizGoodsSkus.sort(Comparator.comparing(SysBizGoodsSku::getMemberSalesPrice));
            //}
            //BigDecimal salesPrice = BigDecimal.ZERO;
            //BigDecimal marketPrice = BigDecimal.ZERO;
            ////SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkus.get(0);
            //// 非会员
            //if (loginUser == null || loginUser.getUserRole() == 0) {
            //    salesPrice = sysBizGoods.getS();
            //    marketPrice = sysBizGoodsSku.getNoMemberMarketPrice();
            //} else {
            //    salesPrice = sysBizGoodsSku.getMemberSalesPrice();
            //    marketPrice = sysBizGoodsSku.getMemberMarketPrice();
            //}

            goodsIndexVoList.add(goodsIndexVo);
        }
        return goodsIndexVoList;
    }

    @Override
    public List<GoodsIndexVo> selectSysBizGoodsByIds(GoodsQueryDto goodsQueryDto, List<Long> ids) {
        List<GoodsIndexVo> goodsIndexVoList = new ArrayList<>();
        LambdaQueryWrapper<SysBizGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(goodsQueryDto.getCategoryId() != null, SysBizGoods::getCategoryId, goodsQueryDto.getCategoryId());
        queryWrapper.eq(goodsQueryDto.getCategoryTwoId() != null, SysBizGoods::getCategoryTwoId, goodsQueryDto.getCategoryTwoId());
        queryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        queryWrapper.eq(SysBizGoods::getGrounding, EnableStatusEnum.ENABLE.getKey());
        queryWrapper.in(!CollectionUtils.isEmpty(ids), SysBizGoods::getId, ids);
        queryWrapper.like(StringUtils.isNotBlank(goodsQueryDto.getGoodsName()), SysBizGoods::getName, goodsQueryDto.getGoodsName());
        setSort(goodsQueryDto, queryWrapper);
        List<SysBizGoods> sysBizGoodsList = list(queryWrapper);
        if (CollectionUtils.isEmpty(sysBizGoodsList)) {
            return goodsIndexVoList;
        }
        for (SysBizGoods sysBizGoods : sysBizGoodsList) {
            GoodsIndexVo goodsIndexVo = new GoodsIndexVo();
            BeanUtils.copyProperties(sysBizGoods, goodsIndexVo);

            goodsIndexVoList.add(goodsIndexVo);
        }

        setOperationTag(goodsQueryDto, goodsIndexVoList);
        return goodsIndexVoList;
    }

    @Override
    public List<GoodsIndexVo> selectSysBizGoodsByIds2(GoodsQueryDto goodsQueryDto, List<Long> ids, Long tenantId, Long userId) {
        List<GoodsIndexVo> goodsIndexVoList = new ArrayList<>();
        LambdaQueryWrapper<SysBizGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(goodsQueryDto.getCategoryId() != null, SysBizGoods::getCategoryId, goodsQueryDto.getCategoryId());
        queryWrapper.eq(goodsQueryDto.getCategoryTwoId() != null, SysBizGoods::getCategoryTwoId, goodsQueryDto.getCategoryTwoId());
        queryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        queryWrapper.eq(SysBizGoods::getGrounding, EnableStatusEnum.ENABLE.getKey());
        queryWrapper.in(!CollectionUtils.isEmpty(ids), SysBizGoods::getId, ids);
        queryWrapper.like(StringUtils.isNotBlank(goodsQueryDto.getGoodsName()), SysBizGoods::getName, goodsQueryDto.getGoodsName());
        setSort(goodsQueryDto, queryWrapper);
        List<SysBizGoods> sysBizGoodsList = list(queryWrapper);
        if (CollectionUtils.isEmpty(sysBizGoodsList)) {
            return goodsIndexVoList;
        }

        SysBizUser loginUser = sysBizUserService.getById(userId == null ? 0L : userId);

        LambdaQueryWrapper<SysBizGoodsSku> query = new LambdaQueryWrapper<>();
        if(!CollectionUtils.isEmpty(ids)){
            query.in(SysBizGoodsSku::getGoodsId, ids);
        }

        query.eq(SysBizGoodsSku::getTenantId,tenantId);
        query.eq(SysBizGoodsSku::getStatus,OrderDeleteEnum.NOT_DELETE.getKey());

        List<SysBizGoodsSku> skuList = goodsSkuService.list(query);
        Map<Long, SysBizGoodsSku> skuInfoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(skuList)) {
            skuList = skuList.stream()
                    .collect(Collectors.groupingBy(SysBizGoodsSku::getGoodsId,
                            Collectors.collectingAndThen(
                                    Collectors.minBy(Comparator.comparing(SysBizGoodsSku::getVip1Price)),
                                    Optional::get
                            )
                    ))
                    .values()
                    .stream()
                    .collect(Collectors.toList());


            // 新增商品信息映射表
            skuInfoMap = skuList.stream()
                    .collect(Collectors.toMap(SysBizGoodsSku::getGoodsId, sku -> sku));
        }

        // 预先生成商品ID到最低VIP价格的映射
        Map<Long, BigDecimal> priceMap = new HashMap<>();
        if (loginUser != null) {
            final int grade = loginUser.getMemberGradeId().intValue();
            priceMap = skuList.stream().collect(Collectors.groupingBy(SysBizGoodsSku::getGoodsId,
                    Collectors.collectingAndThen(
                            Collectors.minBy(Comparator.comparing(s -> {
                                // 新增活动价格优先逻辑
                                if (s.getTag() != null) {
                                    return s.getActivityPrice();
                                }
                                switch (grade) {
                                    case 1: return s.getVip1Price();
                                    case 2: return s.getVip2Price();
                                    case 3: return s.getVip3Price();
                                    case 4: return s.getVip4Price();
                                    case 5: return s.getVip5Price();
                                    default: return BigDecimal.ZERO;
                                }
                            })),
                            opt -> opt.map(s -> {
                                // 新增活动价格优先逻辑
                                if (s.getTag() != null) {
                                    return s.getActivityPrice();
                                }
                                switch (grade) {
                                    case 1: return s.getVip1Price();
                                    case 2: return s.getVip2Price();
                                    case 3: return s.getVip3Price();
                                    case 4: return s.getVip4Price();
                                    case 5: return s.getVip5Price();
                                    default: return BigDecimal.ZERO;
                                }
                            }).orElse(BigDecimal.ZERO)
                    ))
            );
        }

        for (SysBizGoods sysBizGoods : sysBizGoodsList) {
            GoodsIndexVo goodsIndexVo = new GoodsIndexVo();
            BeanUtils.copyProperties(sysBizGoods, goodsIndexVo);

            // 从预生成的映射表获取价格
            if (loginUser != null) {
                goodsIndexVo.setMinSalesPrice(priceMap.getOrDefault(goodsIndexVo.getId(), BigDecimal.ZERO));
                goodsIndexVo.setMaxSalesPrice(priceMap.getOrDefault(goodsIndexVo.getId(), BigDecimal.ZERO));
            }
            // 新增商品名称和单位赋值
            SysBizGoodsSku skuInfo = skuInfoMap.get(goodsIndexVo.getId());
            if (skuInfo != null) {
                goodsIndexVo.setName(skuInfo.getSkuName());
                goodsIndexVo.setUnit(skuInfo.getLongUnit());
            }

            goodsIndexVoList.add(goodsIndexVo);
        }

        setOperationTag(goodsQueryDto, goodsIndexVoList);
        return goodsIndexVoList;
    }

    @Override
    public List<GoodsIndexVo> selectSysBizGoodsBySkuId(GoodsQueryDto goodsQueryDto, List<SysBizGoodsSku> skuList, Long userId) {
        SysBizUser loginUser = sysBizUserService.getById(userId == null ? 0L : userId);

        List<GoodsIndexVo> goodsIndexVoList = new ArrayList<>();
        skuList.forEach(s -> {
            GoodsIndexVo goodsIndexVo = new GoodsIndexVo();
            goodsIndexVo.setActivityPrice(s.getActivityPrice());

            LambdaQueryWrapper<SysBizGoods> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(goodsQueryDto.getCategoryId() != null, SysBizGoods::getCategoryId, goodsQueryDto.getCategoryId());
            queryWrapper.eq(goodsQueryDto.getCategoryTwoId() != null, SysBizGoods::getCategoryTwoId, goodsQueryDto.getCategoryTwoId());
            queryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
            queryWrapper.eq(SysBizGoods::getGrounding, EnableStatusEnum.ENABLE.getKey());
            queryWrapper.eq(SysBizGoods::getId, s.getGoodsId());

            SysBizGoods sysBizGoods = sysBizGoodsMapper.selectOne(queryWrapper);
            if (sysBizGoods != null) {
                BeanUtils.copyProperties(sysBizGoods, goodsIndexVo);
                goodsIndexVoList.add(goodsIndexVo);
            }
            if(s.getTag() != null){
                goodsIndexVo.setMinSalesPrice(s.getActivityPrice());
            }else if (loginUser != null) {
                if (loginUser.getMemberGradeId() == 1) {
                    goodsIndexVo.setMinSalesPrice(s.getVip1Price());
                }
                if (loginUser.getMemberGradeId() == 2) {
                    goodsIndexVo.setMinSalesPrice(s.getVip2Price());
                }
                if (loginUser.getMemberGradeId() == 3) {
                    goodsIndexVo.setMinSalesPrice(s.getVip3Price());
                }
                if (loginUser.getMemberGradeId() == 4) {
                    goodsIndexVo.setMinSalesPrice(s.getVip4Price());
                }
                if (loginUser.getMemberGradeId() == 5) {
                    goodsIndexVo.setMinSalesPrice(s.getVip5Price());
                }
            }

        });
        setOperationTag(goodsQueryDto, goodsIndexVoList);
        return goodsIndexVoList;
    }

    @Override
    public void setOperationTag(GoodsQueryDto goodsQueryDto, List<GoodsIndexVo> goodsIndexVoList) {
        // 获取系统分类数据
        Map<String, SysDictData> dictDataMap = getStringSysDictDataMap();
        Long tenantId = goodsQueryDto.getTenantId();
        // 推荐分类列表
        List<SysBizRecommendCategory> recommendCategoryList = getSysBizRecommendCategories(tenantId);
        Map<Long, SysBizRecommendGoods> goodsRecommendGoodMap = new HashMap<>();

        Map<Long, SysBizRecommendCategory> recommendCategoryMap = new HashMap<>();
        //是否推荐分类
        if (!CollectionUtils.isEmpty(recommendCategoryList)) {
            List<Long> categoryIds = recommendCategoryList.stream().map(p -> p.getId()).collect(Collectors.toList());
            recommendCategoryMap = recommendCategoryList.stream().collect(Collectors.toMap(k -> k.getId(), v -> v, (exists, replace) -> exists));
            goodsRecommendGoodMap = getLongSysBizRecommendGoodsMap(tenantId, goodsRecommendGoodMap, categoryIds);
        }

        // 正在进行的秒杀
        Map<Long, SysBizMarketPageCategory> marketPageCategoryMap = getLongSysBizMarketPageCategoryMap(goodsQueryDto.getTenantId());
        Map<Long, SysBizSeckillPage> seckillPageMap = getKillInfo(tenantId);
        for (GoodsIndexVo goodsIndexVo : goodsIndexVoList) {
            Long id = goodsIndexVo.getId();
            Integer tag = goodsIndexVo.getTag();
            TagVo operationTag = getTagVo(dictDataMap, goodsRecommendGoodMap, recommendCategoryMap, marketPageCategoryMap, seckillPageMap, tag, id);
            goodsIndexVo.setOperationTag(operationTag);
        }
    }

    private Map<Long, SysBizRecommendGoods> getLongSysBizRecommendGoodsMap(Long tenantId, Map<Long, SysBizRecommendGoods> goodsRecommendGoodMap, List<Long> categoryIds) {
        LambdaQueryWrapper<SysBizRecommendGoods> recommendGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();

        recommendGoodsLambdaQueryWrapper.in(SysBizRecommendGoods::getRecommendCategoryId, categoryIds);
        recommendGoodsLambdaQueryWrapper.eq(SysBizRecommendGoods::getDeleted, DeleteEnum.NOT_DELETE.getKey());
        recommendGoodsLambdaQueryWrapper.eq(SysBizRecommendGoods::getTenantId, tenantId);
        List<SysBizRecommendGoods> recommendGoodsList = recommendGoodsService.list(recommendGoodsLambdaQueryWrapper);

        if (!CollectionUtils.isEmpty(recommendGoodsList)) {
            goodsRecommendGoodMap = recommendGoodsList.stream().collect(Collectors.toMap(k -> k.getGoodsId(), v -> v, (exists, replace) -> exists));
        }
        return goodsRecommendGoodMap;
    }

    private List<SysBizRecommendCategory> getSysBizRecommendCategories(Long tenantId) {
        LambdaQueryWrapper<SysBizRecommendCategory> recommendCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        recommendCategoryLambdaQueryWrapper.eq(SysBizRecommendCategory::getDeleted, DeleteEnum.NOT_DELETE.getKey());
        recommendCategoryLambdaQueryWrapper.eq(SysBizRecommendCategory::getRecommendType, 1);
        recommendCategoryLambdaQueryWrapper.eq(SysBizRecommendCategory::getTenantId, tenantId);
        List<SysBizRecommendCategory> recommendCategoryList = recommendCategoryGoodsService.list(recommendCategoryLambdaQueryWrapper);
        return recommendCategoryList;
    }

    public void setOperationTag(Long tenantId, GoodsDetailVo goodsDetailVo) {
        // 获取系统分类数据
        Map<String, SysDictData> dictDataMap = getStringSysDictDataMap();
        // 推荐分类列表
        List<SysBizRecommendCategory> recommendCategoryList = getSysBizRecommendCategories(tenantId);
        Map<Long, SysBizRecommendGoods> goodsRecommendGoodMap = new HashMap<>();

        Map<Long, SysBizRecommendCategory> recommendCategoryMap = new HashMap<>();
        //是否推荐分类
        if (!CollectionUtils.isEmpty(recommendCategoryList)) {
            List<Long> categoryIds = recommendCategoryList.stream().map(p -> p.getId()).collect(Collectors.toList());
            recommendCategoryMap = recommendCategoryList.stream().collect(Collectors.toMap(k -> k.getId(), v -> v, (exists, replace) -> exists));
            goodsRecommendGoodMap = getLongSysBizRecommendGoodsMap(tenantId, goodsRecommendGoodMap, categoryIds);
        }

        // 正在进行的秒杀

        Map<Long, SysBizMarketPageCategory> marketPageCategoryMap = getLongSysBizMarketPageCategoryMap(tenantId);
        Map<Long, SysBizSeckillPage> seckillPageMap = getKillInfo(tenantId);

        Integer tag = goodsDetailVo.getTag();

        Long id = goodsDetailVo.getId();
        TagVo operationTag = getTagVo(dictDataMap, goodsRecommendGoodMap, recommendCategoryMap, marketPageCategoryMap, seckillPageMap, tag, id);
        goodsDetailVo.setOperationTag(operationTag);

    }


    private TagVo getTagVo(Map<String, SysDictData> dictDataMap,
                           Map<Long, SysBizRecommendGoods> goodsRecommendGoodMap,
                           Map<Long, SysBizRecommendCategory> recommendCategoryMap,
                           Map<Long, SysBizMarketPageCategory> marketPageCategoryMap,
                           Map<Long, SysBizSeckillPage> seckillPageMap,
                           Integer tag,
                           Long id) {

        SysBizRecommendGoods sysBizRecommendGoods = goodsRecommendGoodMap.get(id);
        SysBizMarketPageCategory sysBizMarketPageCategory = marketPageCategoryMap.get(id);
        SysBizSeckillPage sysBizSeckillPage = seckillPageMap.get(id);
        LambdaQueryWrapper<SysBizGoodsSku> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.eq(SysBizGoodsSku::getGoodsId, id);
        List<SysBizGoodsSku> list = goodsSkuService.list(objectLambdaQueryWrapper);
        Map<Long, SysBizGoodsSku> skuMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(list)) {
            skuMap = list.stream().collect(Collectors.toMap(k -> k.getId(), v -> v));

            for (SysBizGoodsSku sysBizGoodsSku : list) {
                sysBizMarketPageCategory = marketPageCategoryMap.get(sysBizGoodsSku.getId());
                if (sysBizMarketPageCategory != null) {
                    continue;
                }
            }
            for (SysBizGoodsSku sysBizGoodsSku : list) {
                sysBizRecommendGoods = goodsRecommendGoodMap.get(sysBizGoodsSku.getId());
                if (sysBizRecommendGoods != null) {
                    continue;
                }
            }
        }

        TagVo operationTag = null;
        // 秒杀
        if (sysBizSeckillPage != null) {
            operationTag = new TagVo();
            operationTag.setActivityEndTime(sysBizSeckillPage.getActivityEndTime());
            operationTag.setActivityStartTime(sysBizSeckillPage.getActivityStartTime());
            SysDictData sysDictData = dictDataMap.get("1");
            if (sysDictData != null) {
                operationTag.setName(sysDictData.getDictLabel());
                operationTag.setStyleName(sysDictData.getCssClass());
            } else {
                operationTag.setName("秒杀");
            }
        } else {
            // 推荐标签
            if (sysBizRecommendGoods != null) {
                SysBizRecommendCategory sysBizRecommendCategory = recommendCategoryMap.get(sysBizRecommendGoods.getRecommendCategoryId());
                operationTag = new TagVo();

                // 分类
                if (sysBizRecommendCategory != null) {
                    operationTag.setName(sysBizRecommendCategory.getName());
                    operationTag.setIcon(sysBizRecommendCategory.getIcon());
                    SysDictData sysDictData = dictDataMap.get("2");
                    if (sysDictData != null) {
                        operationTag.setName(sysDictData.getDictLabel());
                        operationTag.setStyleName(sysDictData.getCssClass());
                    } else {
                        operationTag.setName("爆款推荐");
                    }
                }
            } else {
                if (tag != null) {

                    SysDictData sysDictData = dictDataMap.get(String.valueOf(tag));
                    if (sysDictData != null) {
                        operationTag = new TagVo();
                        operationTag.setName(sysDictData.getDictLabel());
                        operationTag.setStyleName(sysDictData.getCssClass());
                    }


                }
            }
        }
        return operationTag;
    }

    /**
     * 查询正在秒杀的商品id
     * @param tenantId 站点id
     * @return 数据
     */
    private Map<Long, SysBizSeckillPage> getKillInfo(Long tenantId) {
        Map<Long, SysBizSeckillPage> killDataMap = new HashMap<>();

        List<SysBizSeckillPage> killPages = sysBizSeckillPageService.list(new LambdaQueryWrapper<SysBizSeckillPage>()
                .eq(SysBizSeckillPage::getTenantId, tenantId)
                .eq(SysBizSeckillPage::getDisplayed, 0));

        if (!CollectionUtils.isEmpty(killPages)) {
            SysBizSeckillPage seckillPage = killPages.get(0);
            // 查询对应的商品信息
            List<SysBizSeckillGoodsPage> pageList = sysBizSeckillGoodsPageService.selectSysBizSeckillGoodsPageList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                    .eq(SysBizSeckillGoodsPage::getSeckillId, seckillPage.getId())
                    .eq(SysBizSeckillGoodsPage::getTenantId, tenantId));

            if (!CollectionUtils.isEmpty(pageList)) {
                List<Long> longs = new ArrayList<>();
                for (SysBizSeckillGoodsPage sysBizSeckillGoodsPage : pageList) {
                    List<Long> collect = Arrays.stream(sysBizSeckillGoodsPage.getGoodsId().split(",")).map(Long::parseLong).collect(Collectors.toList());
                    longs.addAll(collect);
                }

                List<SysBizGoodsSku> skuList = sysBizGoodsSkuMapper.selectList(
                        new LambdaQueryWrapper<SysBizGoodsSku>().in(SysBizGoodsSku::getId, longs));

                List<Long> collect = skuList.stream().map(SysBizGoodsSku::getGoodsId).distinct().collect(Collectors.toList());

                if (!CollectionUtils.isEmpty(collect)) {
                    collect.forEach(g -> {
                        killDataMap.put(g, seckillPage);
                    });

                }
            }
        }
        return killDataMap;
    }

    private Map<Long, SysBizMarketPageCategory> getLongSysBizMarketPageCategoryMap(Long tenantId) {
        LambdaQueryWrapper<SysBizMarketPageCategory> marketPageCategoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        marketPageCategoryLambdaQueryWrapper.eq(SysBizMarketPageCategory::getActivityType, 1);
        marketPageCategoryLambdaQueryWrapper.eq(SysBizMarketPageCategory::getTenantId, tenantId);
        marketPageCategoryLambdaQueryWrapper.le(SysBizMarketPageCategory::getActivityStartTime, LocalDateTime.now());
        marketPageCategoryLambdaQueryWrapper.ge(SysBizMarketPageCategory::getActivityEndTime, LocalDateTime.now());
        marketPageCategoryLambdaQueryWrapper.isNotNull(SysBizMarketPageCategory::getGoodsId);
        marketPageCategoryLambdaQueryWrapper.eq(SysBizMarketPageCategory::getDeleted, DeleteEnum.NOT_DELETE.getKey());
        marketPageCategoryLambdaQueryWrapper.eq(SysBizMarketPageCategory::getDisplayed, DeleteEnum.NOT_DELETE.getKey());
        List<SysBizMarketPageCategory> pageCategoryList = marketPageCategoryService.list(marketPageCategoryLambdaQueryWrapper);


        Map<Long, SysBizMarketPageCategory> marketPageCategoryMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(pageCategoryList)) {
            for (SysBizMarketPageCategory sysBizMarketPageCategory : pageCategoryList) {

                String goodsId = sysBizMarketPageCategory.getGoodsId();

                if (StringUtils.isEmpty(goodsId)) {
                    continue;
                }
                String[] split = goodsId.split(",");
                for (String gid : split) {
                    marketPageCategoryMap.put(Long.parseLong(gid), sysBizMarketPageCategory);
                }
            }
        }
        return marketPageCategoryMap;
    }

    private Map<String, SysDictData> getStringSysDictDataMap() {
        SysDictData dictData = new SysDictData();
        dictData.setDictType("biz_sales_tag");
        List<SysDictData> sysDictDataList = dictDataService.selectDictDataList(dictData);
        Map<String, SysDictData> dictDataMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(sysDictDataList)) {
            dictDataMap = sysDictDataList.stream().collect(Collectors.toMap(k -> k.getDictValue(), v -> v, (exists, replace) -> exists));

        }
        return dictDataMap;
    }


    private List<SysBizGoods> getSysBizGoods(GoodsQueryDto goodsQueryDto, List<Long> ids) {
        LambdaQueryWrapper<SysBizGoods> sysBizGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizGoodsLambdaQueryWrapper.eq(goodsQueryDto.getCategoryId() == null && StringUtils.isBlank(goodsQueryDto.getGoodsName()), SysBizGoods::getIsRecommend, 0);
        sysBizGoodsLambdaQueryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());

        sysBizGoodsLambdaQueryWrapper.eq(SysBizGoods::getTenantId, goodsQueryDto.getTenantId());
        sysBizGoodsLambdaQueryWrapper.eq(SysBizGoods::getGrounding, EnableStatusEnum.ENABLE.getKey());
//        sysBizGoodsLambdaQueryWrapper.notIn(!CollectionUtils.isEmpty(ids), SysBizGoods::getCategoryId, ids);
        sysBizGoodsLambdaQueryWrapper.eq(goodsQueryDto.getCategoryId() != null, SysBizGoods::getCategoryId, goodsQueryDto.getCategoryId());
        sysBizGoodsLambdaQueryWrapper.eq(goodsQueryDto.getCategoryTwoId() != null, SysBizGoods::getCategoryTwoId, goodsQueryDto.getCategoryTwoId());
        sysBizGoodsLambdaQueryWrapper.notIn(goodsQueryDto.getExcludeGoodsId() != null, SysBizGoods::getId, goodsQueryDto.getExcludeGoodsId());

        sysBizGoodsLambdaQueryWrapper.like(StringUtils.isNotBlank(goodsQueryDto.getGoodsName()), SysBizGoods::getName, goodsQueryDto.getGoodsName());
        return sysBizGoodsMapper.selectList(sysBizGoodsLambdaQueryWrapper);
    }


    @Override
    public GoodsDetailVo queryGoodsDetail(Long id, Long userId, Long tenantId) {
        SysBizUser loginUser = null;
        if (userId != null) {
            loginUser = sysBizUserService.selectSysBizUserById(userId);
        }
        GoodsDetailVo goodsDetailVo = new GoodsDetailVo();
        List<GoodsSkuVo> skuVoList = new ArrayList<>();
        SysBizGoods sysBizGoods = sysBizGoodsMapper.selectById(id);
        BeanUtils.copyProperties(sysBizGoods, goodsDetailVo);
        goodsDetailVo.setIsCollect(Boolean.FALSE);
        if (loginUser != null) {
            List<SysBizUserCollect> sysBizUserCollects = sysBizUserCollectService.selectSysBizUserCollectList(new LambdaQueryWrapper<SysBizUserCollect>().eq(SysBizUserCollect::getUserId, loginUser.getId()).eq(SysBizUserCollect::getGoodsId, id).eq(SysBizUserCollect::getType, CollectionTypeEnum.GOOD.getKey()));
            if (!CollectionUtils.isEmpty(sysBizUserCollects)) {
                goodsDetailVo.setIsCollect(Boolean.TRUE);
            }
        }
        Long sales = 0L;
        // 查询sku列表
        List<SysBizGoodsSku> sysBizGoodsSkus = sysBizGoodsSkuMapper.selectList(new LambdaQueryWrapper<SysBizGoodsSku>().eq(SysBizGoodsSku::getGoodsId, sysBizGoods.getId()));
        // 查询秒杀产品id
        List<Long> skuList = new ArrayList<>();
        List<SysBizSeckillPage> killPages = sysBizSeckillPageService.list(new LambdaQueryWrapper<SysBizSeckillPage>()
                .eq(SysBizSeckillPage::getTenantId, tenantId)
                .eq(SysBizSeckillPage::getDisplayed, 0));

        if (!CollectionUtils.isEmpty(killPages)) {
            SysBizSeckillPage seckillPage = killPages.get(0);
            // 查询对应的商品信息
            List<SysBizSeckillGoodsPage> pageList = sysBizSeckillGoodsPageService.selectSysBizSeckillGoodsPageList(new LambdaQueryWrapper<SysBizSeckillGoodsPage>()
                    .eq(SysBizSeckillGoodsPage::getSeckillId, seckillPage.getId())
                    .eq(SysBizSeckillGoodsPage::getTenantId, tenantId));

            if (!CollectionUtils.isEmpty(pageList)) {
                for (SysBizSeckillGoodsPage sysBizSeckillGoodsPage : pageList) {
                    List<Long> collect = Arrays.stream(sysBizSeckillGoodsPage.getGoodsId().split(",")).map(Long::parseLong).collect(Collectors.toList());
                    skuList.addAll(collect);
                }
            }
        }

        for (SysBizGoodsSku bizGoodsSkus : sysBizGoodsSkus) {
            // 如果sku禁止，并且是单规格的，删除规格信息，多规格的不用删，前端会判断
            if (bizGoodsSkus.getStatus() == 1) {
                if (goodsDetailVo.getSpecsList().size() == 1) {
                    for (SpecsData specsData : sysBizGoods.getSpecsList()) {
                        specsData.getChilds().removeIf(i -> i.getSpecsName().equals(bizGoodsSkus.getSpecsKey()));
                    }
                }
                continue;
            }
            GoodsSkuVo goodsSkuVo = new GoodsSkuVo();
            BeanUtils.copyProperties(bizGoodsSkus, goodsSkuVo);
            BigDecimal salesPrice = null;
            BigDecimal marketPrice = null;
            if(bizGoodsSkus.getTag() != null){
                salesPrice = bizGoodsSkus.getActivityPrice();
                marketPrice = bizGoodsSkus.getActivityPrice();
            }else if (loginUser != null) {
                if (loginUser.getMemberGradeId() == 1) {
                    salesPrice = bizGoodsSkus.getVip1Price();
                    marketPrice = bizGoodsSkus.getVip1Price();
                }
                if (loginUser.getMemberGradeId() == 2) {
                    salesPrice = bizGoodsSkus.getVip2Price();
                    marketPrice = bizGoodsSkus.getVip2Price();
                }
                if (loginUser.getMemberGradeId() == 3) {
                    salesPrice = bizGoodsSkus.getVip3Price();
                    marketPrice = bizGoodsSkus.getVip3Price();
                }
                if (loginUser.getMemberGradeId() == 4) {
                    salesPrice = bizGoodsSkus.getVip4Price();
                    marketPrice = bizGoodsSkus.getVip4Price();
                }
                if (loginUser.getMemberGradeId() == 5) {
                    salesPrice = bizGoodsSkus.getVip5Price();
                    marketPrice = bizGoodsSkus.getVip5Price();
                }
            } else {
                salesPrice = bizGoodsSkus.getMemberSalesPrice();
                marketPrice = bizGoodsSkus.getMemberMarketPrice();
            }
            sales += bizGoodsSkus.getSales();
            goodsSkuVo.setSalesPrice(salesPrice);
            goodsSkuVo.setMarketPrice(marketPrice);
            goodsSkuVo.setStockCount(bizGoodsSkus.getStock() - bizGoodsSkus.getFrozenStockCount());
            goodsSkuVo.setLongUnit(bizGoodsSkus.getLongUnit());
            goodsSkuVo.setSkuName(bizGoodsSkus.getSkuName());
            goodsSkuVo.setIsKillProduct(skuList.contains(bizGoodsSkus.getId()));
            skuVoList.add(goodsSkuVo);
        }
        goodsDetailVo.setActualSales(sysBizGoods.getActualSales() + sales);

        BigDecimal salesPrice = null;
        BigDecimal marketPrice = null;
        if (CollectionUtils.isEmpty(sysBizGoodsSkus)) {
            return goodsDetailVo;
        }
        if (loginUser == null || loginUser.getUserRole() == 0) {
            sysBizGoodsSkus.sort(Comparator.comparing(SysBizGoodsSku::getMemberMarketPrice));
        } else {
            sysBizGoodsSkus.sort(Comparator.comparing(SysBizGoodsSku::getMemberSalesPrice));
        }
        SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkus.get(0);
        if (loginUser != null) {
            if (loginUser.getMemberGradeId() == 1) {
                salesPrice = sysBizGoodsSku.getVip1Price();
                marketPrice = sysBizGoodsSku.getVip1Price();
            }
            if (loginUser.getMemberGradeId() == 2) {
                salesPrice = sysBizGoodsSku.getVip2Price();
                marketPrice = sysBizGoodsSku.getVip2Price();
            }
            if (loginUser.getMemberGradeId() == 3) {
                salesPrice = sysBizGoodsSku.getVip3Price();
                marketPrice = sysBizGoodsSku.getVip3Price();
            }
            if (loginUser.getMemberGradeId() == 4) {
                salesPrice = sysBizGoodsSku.getVip4Price();
                marketPrice = sysBizGoodsSku.getVip4Price();
            }
            if (loginUser.getMemberGradeId() == 5) {
                salesPrice = sysBizGoodsSku.getVip5Price();
                marketPrice = sysBizGoodsSku.getVip5Price();
            }
        } else {
            salesPrice = sysBizGoodsSku.getMemberSalesPrice();
            marketPrice = sysBizGoodsSku.getMemberMarketPrice();
        }
        goodsDetailVo.setSalesPrice(salesPrice);
        goodsDetailVo.setMarketPrice(marketPrice);
        // 在设置sku列表前添加排序
        skuVoList.sort(Comparator.comparing(GoodsSkuVo::getVip1Price));
        goodsDetailVo.setSysBizGoodsSkuList(skuVoList);
        goodsDetailVo.setUnit(sysBizGoodsSku.getLongUnit());
        setOperationTag(tenantId, goodsDetailVo);//luo

        return goodsDetailVo;
    }

    @Override
    public boolean hasCategory(Long id) {
        LambdaQueryWrapper<SysBizGoods> sysBizGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysBizGoodsLambdaQueryWrapper.eq(SysBizGoods::getCategoryId, id);
        sysBizGoodsLambdaQueryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey());
        List<SysBizGoods> sysBizGoods = sysBizGoodsMapper.selectList(sysBizGoodsLambdaQueryWrapper);
        return !sysBizGoods.isEmpty();
    }

    @Override
    public void lockSales(Long goodsId, Long number) {
        sysBizGoodsMapper.lockSales(goodsId, number);
    }

    @Override
    public List<SysBizGoods> getGoodsList(GoodsQueryDto goodsQueryDto, HashMap<String, String> wordMap) {
        String goodsName = goodsQueryDto.getGoodsName();
        QueryWrapper<SysBizGoods> sysBizGoodsLambdaQueryWrapper = new QueryWrapper<>();
        sysBizGoodsLambdaQueryWrapper.eq(goodsQueryDto.getCategoryId() == null && StringUtils.isBlank(goodsName), "is_recommend", 0);
        sysBizGoodsLambdaQueryWrapper.eq("deleted", OrderDeleteEnum.NOT_DELETE.getKey());
        sysBizGoodsLambdaQueryWrapper.eq("tenant_id", goodsQueryDto.getTenantId());
        sysBizGoodsLambdaQueryWrapper.eq(goodsQueryDto.getCategoryTwoId() != null, "category_two_id", goodsQueryDto.getCategoryTwoId());
        sysBizGoodsLambdaQueryWrapper.eq("grounding", EnableStatusEnum.ENABLE.getKey());
        sysBizGoodsLambdaQueryWrapper.eq(goodsQueryDto.getCategoryId() != null, "category_id", goodsQueryDto.getCategoryId());
        sysBizGoodsLambdaQueryWrapper.like(StringUtils.isNotBlank(goodsName), "name", goodsName);
        if (StringUtils.isEmpty(goodsQueryDto.getPriceFlag()) && StringUtils.isEmpty(goodsQueryDto.getSalesNumFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByDesc("order_num");
        }

        List<String> words = new ArrayList<>(wordMap.keySet());
        if (!CollectionUtils.isEmpty(words)) {
            int size = words.size();
            int maxIndex = Math.min(size, 8); // 只处理前8个关键词
            sysBizGoodsLambdaQueryWrapper.and(p -> {
                for (int i = 0; i < maxIndex; i++) {
                    String keyword = words.get(i);
                    if (StringUtils.isNotEmpty(keyword)) {
                        p.or().like("name", keyword)
                                .or().like("prop_tags", keyword);
                    }
                }
            });
        }
        // 处理搜索排序 + 用户自定义排序
        String searchValue = goodsQueryDto.getSearchValue();
        StringBuilder orderByBuilder = new StringBuilder();

        // 1. 处理搜索词排序
        if (StringUtils.isNotBlank(searchValue)) {
            String safeSearch = searchValue.trim().replace("'", "''");
            orderByBuilder.append(String.format(
                    "CASE WHEN LOCATE('%s', name) > 0 THEN 0 ELSE 1 END ASC", safeSearch
            ));
        }

        // 2. 处理价格排序
        if ("0".equals(goodsQueryDto.getPriceFlag())) {
            if (orderByBuilder.length() > 0) {
                orderByBuilder.append(", ");
            }
            orderByBuilder.append("min_market_price ASC");
        } else if ("1".equals(goodsQueryDto.getPriceFlag())) {
            if (orderByBuilder.length() > 0) {
                orderByBuilder.append(", ");
            }
            orderByBuilder.append("min_market_price DESC");
        }

        // 3. 处理销量排序
        if ("0".equals(goodsQueryDto.getSalesNumFlag())) {
            if (orderByBuilder.length() > 0) {
                orderByBuilder.append(", ");
            }
            orderByBuilder.append("reality_sales ASC");
        } else if ("1".equals(goodsQueryDto.getSalesNumFlag())) {
            if (orderByBuilder.length() > 0) {
                orderByBuilder.append(", ");
            }
            orderByBuilder.append("reality_sales DESC");
        }

        // 4. 默认兜底排序（可选）
        if (orderByBuilder.length() > 0) {
            // 5. 应用最终排序
            sysBizGoodsLambdaQueryWrapper.last("ORDER BY " + orderByBuilder.toString());
        }

        return selectSysBizGoodsList(sysBizGoodsLambdaQueryWrapper);
    }

    @Override
    public int lockStocks(Long id, Long number) {
        return sysBizGoodsMapper.lockStocks(id, number);
    }

    @Override
    public void releaseStocks(Long id, Long number) {
        sysBizGoodsMapper.releaseStocks(id, number);
    }

    private void setSort(GoodsQueryDto goodsQueryDto, LambdaQueryWrapper<SysBizGoods> sysBizGoodsLambdaQueryWrapper) {
        if ("0".equals(goodsQueryDto.getPriceFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByAsc(SysBizGoods::getMinMarketPrice);
        } else if ("1".equals(goodsQueryDto.getPriceFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByDesc(SysBizGoods::getMinMarketPrice);
        }
        if ("0".equals(goodsQueryDto.getSalesNumFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByAsc(SysBizGoods::getRealitySales);
        } else if ("1".equals(goodsQueryDto.getSalesNumFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByDesc(SysBizGoods::getRealitySales);
        }
    }

    private void setSort(GoodsQueryDto goodsQueryDto, QueryWrapper<SysBizGoods> sysBizGoodsLambdaQueryWrapper) {
        if ("0".equals(goodsQueryDto.getPriceFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByAsc("min_market_price");
        } else if ("1".equals(goodsQueryDto.getPriceFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByDesc("min_market_price");
        }
        if ("0".equals(goodsQueryDto.getSalesNumFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByAsc("reality_sales");
        } else if ("1".equals(goodsQueryDto.getSalesNumFlag())) {
            sysBizGoodsLambdaQueryWrapper.orderByDesc("reality_sales");
        }
    }
}
